package net.xdclass.component;

import cn.felord.payment.wechat.v3.WechatDirectPayApi;
import cn.felord.payment.wechat.v3.WechatResponseEntity;
import cn.felord.payment.wechat.v3.model.*;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.WechatPayConfig;
import net.xdclass.vo.PayInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * 小滴课堂,愿景：让技术不再难学
 *
 * @Description  微信支付
 * @Author 二当家小D
 * @Remark 有问题直接联系我，源码-笔记-技术交流群
 * @Version 1.0
 **/

@Service
@Slf4j
public class WechatPayStrategy  implements  PayStrategy{


    @Autowired
    private WechatPayConfig payConfig;

    @Autowired
    private WechatDirectPayApi wechatPayService;



    @Override
    public String unifiedOrder(PayInfoVO payInfoVO) {
        /**
         *
         * HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/native");
         *   // 请求body参数
         *   String reqdata = "{"
         *           + "\"time_expire\":\"2018-06-08T10:34:56+08:00\","
         *           + "\"amount\": {"
         *           + "\"total\":100,"
         *           + "\"currency\":\"CNY\""
         *           + "},"
         *           + "\"mchid\":\"1230000109\","
         *           + "\"description\":\"Image形象店-深圳腾大-QQ公仔\","
         *           + "\"notify_url\":\"https://www.weixin.qq.com/wxpay/pay.php\","
         *           + "\"out_trade_no\":\"1217752501201407033233368018\","
         *           + "\"goods_tag\":\"WXG\","
         *           + "\"appid\":\"wxd678efh567hg6787\","
         *           + "\"attach\":\"自定义数据说明\","
         *           + "\"detail\": {"
         *           + "\"invoice_id\":\"wx123\","
         *           + "\"goods_detail\": ["
         *           + "{"
         *           + "\"goods_name\":\"iPhoneX 256G\","
         *           + "\"wechatpay_goods_id\":\"1001\","
         *           + "\"quantity\":1,"
         *           + "\"merchant_goods_id\":\"商品编码\","
         *           + "\"unit_price\":828800"
         *           + "},"
         *           + "{"
         *           + "\"goods_name\":\"iPhoneX 256G\","
         *           + "\"wechatpay_goods_id\":\"1001\","
         *           + "\"quantity\":1,"
         *           + "\"merchant_goods_id\":\"商品编码\","
         *           + "\"unit_price\":828800"
         *           + "}"
         *           + "],"
         *           + "\"cost_price\":608800"
         *           + "},"
         *           + "\"scene_info\": {"
         *           + "\"store_info\": {"
         *           + "\"address\":\"广东省深圳市南山区科技中一道10000号\","
         *           + "\"area_code\":\"440305\","
         *           + "\"name\":\"腾讯大厦分店\","
         *           + "\"id\":\"0001\""
         *           + "},"
         *           + "\"device_id\":\"013467007045764\","
         *           + "\"payer_client_ip\":\"14.23.150.211\""
         *           + "}"
         *           + "}";
         */
        PayParams payParams = new PayParams();


        DateTime expire = DateUtil.date(new Date(System.currentTimeMillis() + payInfoVO.getOrderPayTimeoutMills()));
        String expireDateStr = DateUtil.format(expire,DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        payParams.setAppid(payConfig.getAppId());
        payParams.setMchid(payConfig.getMchId());
        payParams.setDescription(payInfoVO.getTitle());
        payParams.setOutTradeNo(payInfoVO.getOutTradeNo());
        payParams.setNotifyUrl(payConfig.getNotifyUrl());


//        2018-06-08T10:34:56+08:00[
        payParams.setTimeExpire(expireDateStr);
        payParams.setGoodsTag(payInfoVO.getTitle());
        Amount amount = new Amount();
        amount.setTotal(payInfoVO.getPayFee());
        payParams.setAmount(amount);
        JSONObject obj = JSONUtil.createObj();
        obj.set("accountNo", payInfoVO.getAccountNo());

        payParams.setAttach(obj.toString());


        log.info("下单支付参数：{}", JSONUtil.toJsonStr(payParams));


        WechatResponseEntity<ObjectNode> objectNodeWechatResponseEntity = wechatPayService.nativePay(payParams);
        log.info(objectNodeWechatResponseEntity.toString());

//        	 *WechatResponseEntity(httpStatus=200, body={"code_url":"weixin://wxpay/bizpayurl?pr=Lnawvu5zz"})

        return objectNodeWechatResponseEntity.getBody().findValue("code_url").toString();

    }

    @Override
    public String refund(PayInfoVO payInfoVO) {


        RefundParams refundParams = new RefundParams();
        refundParams.setOutTradeNo(payInfoVO.getOutTradeNo());
        refundParams.setOutRefundNo(RandomUtil.randomString(20));
        refundParams.setReason("退款原因");
        refundParams.setNotifyUrl(payConfig.getDomain());
        RefundGoodsDetail refundGoodsDetail = new RefundGoodsDetail();
        refundGoodsDetail.setGoodsName("商品名称");
        refundGoodsDetail.setMerchantGoodsId(RandomUtil.randomString(10));
        refundGoodsDetail.setWechatpayGoodsId(RandomUtil.randomString(10));
        refundGoodsDetail.setUnitPrice(1);
        refundGoodsDetail.setRefundAmount(1);
        refundGoodsDetail.setRefundQuantity(1);

        refundParams.setGoodsDetail(List.of(refundGoodsDetail));
        RefundParams.RefundAmount refundAmount = new RefundParams.RefundAmount();
        refundAmount.setRefund(1);
        refundAmount.setTotal(1);
        refundParams.setAmount(refundAmount);
        log.info("请求参数:{}", refundParams.toString());
        WechatResponseEntity<ObjectNode> refund = wechatPayService.refund(refundParams);
        log.info("退款返回值：{}", refund);
        return null;
    }

    /**
     * 微信支付查询订单状态
     *  * {"amount":{"payer_currency":"CNY","total":100},"appid":"wx5beac15ca207c40c",
     * 	 * "mchid":"1601644442","out_trade_no":"fRAv2Ccpd8GxNEpKAt36X0fdL7WYbn0F",
     * 	 * "promotion_detail":[],"scene_info":{"device_id":""},
     * 	 * "trade_state":"NOTPAY","trade_state_desc":"订单未支付"}
     * @param payInfoVO
     * @return
     */
    @Override
    public String queryPayStatus(PayInfoVO payInfoVO) {
        TransactionQueryParams transactionQueryParams = new TransactionQueryParams();
        transactionQueryParams.setMchId(payConfig.getMchId());
        transactionQueryParams.setTransactionIdOrOutTradeNo("HNq09LdrkmGLRnOM1eZGm6QwqoxnBONK");

        WechatResponseEntity<ObjectNode> response = wechatPayService.queryTransactionByOutTradeNo(transactionQueryParams);
        log.info("response：{}", response);

        return response.getBody().findValue("trade_state").toString();

    }


    @Override
    public String closeOrder(PayInfoVO payInfoVO) {
        WechatResponseEntity<ObjectNode> close = wechatPayService.close(payInfoVO.getOutTradeNo());
        log.info("关闭订单的返回值：{}", close);
        return "OK";
    }

}
